package com.vic.kjlink.simpletools.attachment.controller;

import com.vic.kjlink.simpletools.attachment.constant.AttachmentConstant;
import com.vic.kjlink.simpletools.attachment.service.AttachmentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.vic.boot.base.model.BaseResponse;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @description: 附件处理controller
 * @author Vic.xu
 * @date: 2021/9/17 0017 10:16
 */
@Controller
@RequestMapping(value = "/attachment")
public class AttachmentController {

    private Logger logger = LoggerFactory.getLogger(AttachmentController.class);

    @Resource
    private AttachmentService attachmentService;

    @GetMapping(value = {"", "/"})
    public String index(HttpServletRequest request, Model model) {
        model.addAttribute("wsUrl", wsUrl(request));
        return "attachment";
    }

    @RequestMapping("check")
    @ResponseBody
    public BaseResponse check(@RequestParam(defaultValue = "") String sql) {
        BaseResponse<String> response = attachmentService.check(sql);
        return response;
    }

    @RequestMapping("handle")
    @ResponseBody
    public BaseResponse handle(@RequestParam(defaultValue = "") String sql, String target) {
        BaseResponse response = attachmentService.handle(sql, target);
        return response;
    }

    /**
     * 获取websocket的连接地址
     * @param request
     * @return
     */
    private String wsUrl(HttpServletRequest request) {
        String serverName = request.getServerName();
        String contextPath = request.getContextPath();
        int serverPort = request.getServerPort();
        String ws = "wss://";

        String scheme = request.getScheme();
        if ("http".equalsIgnoreCase(scheme)) {
            ws = "ws://";
        }
        String url = ws + serverName + ":" + serverPort + "/" + contextPath + AttachmentConstant.SOCKET_URL;
        ;
        logger.info("scheme:[{}];serverName:[{}];serverPort:[{}];contextPath[{}]", new Object[]{scheme, serverName, serverPort, contextPath});
        return url;


    }
}